// page/component/new-pages/cart/cart.js

var goods_table = require('../../template/goodsTable/goods_table.js')
Page({
  data: {
    cart: [], // 购物车列表
    goods: [],
    userAddress: {},
    editTxt: '编辑',
    hasList: false, // 列表是否有数据
    totalPrice: 0, // 总价，初始为0
    selectAllStatus: false, // 全选状态，默认不选,
    isLoadOver: false
  },
  //
  goAddress(e) {
    wx.navigateTo({
      url: '/views/userCenter/addresses/addresses',
    })
  },
  /**
   * 当前商品选中事件
   */
  selectList(e) {
    const index = e.currentTarget.dataset.index;
    let cart = this.data.cart;
    const selected = cart[index].selected;
    cart[index].selected = !selected;
    this.setData({
      cart: cart
    });
    this.getTotalPrice();
  },

  /**
   * 购物车全选事件
   */
  selectAll(e) {
    let selectAllStatus = this.data.selectAllStatus;
    selectAllStatus = !selectAllStatus;
    let cart = this.data.cart;

    for (let i = 0; i < cart.length; i++) {
      cart[i].selected = selectAllStatus;
    }
    this.setData({
      selectAllStatus: selectAllStatus,
      cart: cart
    });
    this.getTotalPrice();

    if (cart.length > 0) {

    }
  },

  /********编辑购物车********/
  editCart: function (e) {
    if (this.data.editTxt == '编辑') {
      this.setData({
        editTxt: '完成'
      });
    } else {
      this.setData({
        editTxt: '编辑',
        selectAllStatus: false
      });
    }

  },
  /**********删除购物车***********/
  delCart: function (e) {
    var that = this;
    var db = wx.cloud.database();
    const query = wx.createSelectorQuery();
    query.selectAll('.slected').fields({
      dataset: true,
    }, function (res) {
      //多条数据一直删除不了，后续用云函数试
      res.forEach(x => {
        db.collection('cart').where({
          _id: x.dataset.id
        }).remove();
      });
      that.loadCart();
      // if (ids.length > 0) {
      //   //云函数删除购物车

      // }
    }).exec();
  },
  /**
   * 绑定加数量事件
   */
  addCount(e) {
    const index = e.currentTarget.dataset.index;
    let cart = this.data.cart;
    let num = cart[index].count;
    num = num + 1;
    cart[index].count = num;
    this.setData({
      cart: cart
    });
    this.getTotalPrice();
    var db = wx.cloud.database();
    db.collection("cart").where({
      _id: cart[index]._id
    }).update({
      data: {
        count: num
      }
    });
  },

  /**
   * 绑定减数量事件
   */
  minusCount(e) {
    const index = e.currentTarget.dataset.index;
    const obj = e.currentTarget.dataset.obj;
    let cart = this.data.cart;
    let num = cart[index].count;
    if (num <= 1) {
      return false;
    }
    num = num - 1;
    cart[index].count = num;
    this.setData({
      cart: cart
    });
    this.getTotalPrice();
    var db = wx.cloud.database();
    db.collection("cart").where({
      _id: cart[index]._id
    }).update({
      data: {
        count: num
      }
    });
  },
  goOrder: function (e) {
    if (this.data.totalPrice == 0) {
      wx.showToast({
        title: '请勾选要结算的商品',
        icon: "none"
      })
      return;
    }
    wx.navigateTo({
      url: '/views/goods/payOrder/payOrder',
    })

  },
  /**
   * 计算总价
   */
  getTotalPrice() {
    let cart = this.data.cart; // 获取购物车列表
    let total = 0;
    for (let i = 0; i < cart.length; i++) { // 循环列表得到每个数据
      if (cart[i].selected) { // 判断选中才会计算价格
        total += cart[i].count * cart[i].price; // 所有价格加起来
      }
    }
    var select_goods = goods_table.getGoods();

    this.setData({ // 最后赋值到data中渲染到页面
      cart: cart,
      totalPrice: total.toFixed(2),
      hasList: true,
      goods: select_goods
    });
  },
  GoGoodsDetail: function (e) {
    wx.navigateTo({
      url: '../goods/detail/detail?id=' + e.currentTarget.dataset.id
    })
  },
  //登录信息失效/未注册新用户
  noLogin: function (e) {
    this.setData({
      hasList: false
    });
    var that = this;
    //var db = wx.cloud.database();

    that.setData({
      goods: [],
      hasList: false,
      isLoadOver: true
    });
    that.loading = that.selectComponent("#loading");
    that.loading.HideLoading();
  },
  /**加载购物车*/

  loadCart: function (e) {
    var currentDate = new Date();
    var week = currentDate.getDay();
    var hour = currentDate.getHours();
    // if ((week == 2 || week == 5)&&hour==0) //每周二、五凌晨清空购物车，避免产生永久缓存数据    
    //    wx.clearStorage();
    
    var that = this;
    wx.getStorage({
      key: 'cart',
      complete(res) {
        if (res.data) {
          that.setData({
            cart: res.data,
            hasList:true,
            isLoadOver: true
          });
        }
      }
    })
    this.getTotalPrice();
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.loadCart();
    this.loading = this.selectComponent("#loading");
    this.loading.HideLoading();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    var that = this;
    that.setData({
      goods: [],
      cart: [],
      isLoadOver: false
    });
    this.loading = this.selectComponent("#loading");
    this.loading.ShowLoading();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

})